<?php

class RedisBaseModel {

    public function __construct() {
        
    }
    
    /**
     *
     * @param string $key
     * @param any $value
     * @param integer $seconds
     * @param string $namespace NOT RELEASED
     * @return boolean 
     */
    public function set($key, $value, $seconds = null, $namespace = null) {
        $rediska = new Rediska_Key($key);
        if($seconds) {
            return $rediska->setAndExpire($value, $seconds);
        } else {
            return $rediska->setValue($value);
        }
    }
    
    
    /**
     * @param string|array $key
     */
    public function get($key) {
        $rediska = new Rediska_Key($key);
        return $rediska->getValue();
    }
    
    /**
     *
     * @param string $key
     * @return boolean 
     */
    public function exists($key) {
        return Yii::app()->rediska->connect()->exists($key);
    }
    
    /**
     *
     * @param string $key
     * @return boolean 
     */
    public function delete($key) {
        $rediska = new Rediska_Key($key);
        return $rediska->delete();
    }


    /**
     * Return object of Rediska_Key_SortedSet
     * @param string $key
     * @return Rediska_Key_SortedSet 
     */
    public function zcreate($key) {
        return new Rediska_Key_SortedSet($key);
    }

    /**
     * Add/update member in sorted set
     * @param string $key
     * @param integer $score
     * @param string $member
     * @param integer $seconds
     * @return Rediska_Key_SortedSet 
     */
    public function zadd($key, $score, $member) {
        $sortedSet = new Rediska_Key_SortedSet($key);
        $sortedSet->add($member, $score);        
        return $sortedSet;
    }
    

    /**
     * Remove member in sorted set
     * @param string $key
     * @param string $member
     * @return boolean 
     */
    public function zrem($key, $member) {
        $sortedSet = new Rediska_Key_SortedSet($key);
        return $sortedSet->remove($member);
    }
    
    /**
     * Return count of sorted set
     * @param string $key
     * @return integer 
     */
    public function zcount($key) {
        $sortedSet = new Rediska_Key_SortedSet($key);
        return $sortedSet->count();
    }

    
    /**
     * Intersection of sets
     * @param array $sortedSets Rediska_Key_SortedSet or string
     * @param string $resultName
     * @param string $aggregation MIN, MAX, default SUM
     * @return string 
     */
    public function zinterstore($sortedSets, $resultName, $aggregation = "SUM") {
        $redis = new Rediska_Key_SortedSet(array_shift($sortedSets));
        if($redis->intersect($sortedSets, $resultName, $aggregation)) {
            return $resultName;
        }else
            return false;
    }

}

